<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\Tenant\StoreTaskRequest;
use App\Models\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class TaskController extends Controller
{
    /**
     * 获取任务列表
     */
    public function index(Request $request)
    {
        $query = Task::where('tenant_id', $request->user()->tenant_id)
        // $query = Task::where('tenant_id', 2)
                    ->with(['applications.freelancer']);

        // 搜索过滤
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('work_content', 'like', "%{$search}%")
                  ->orWhere('work_location', 'like', "%{$search}%");
            });
        }

        // 状态过滤
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // 服务类型过滤
        if ($request->filled('service_type')) {
            $query->where('service_type', $request->service_type);
        }

        // 时间范围过滤
        if ($request->filled('start_date')) {
            $query->where('start_time', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->where('end_time', '<=', $request->end_date);
        }

        // 排序
        $sortBy = $request->get('sort_by', 'created_at');
        $sortOrder = $request->get('sort_order', 'desc');
        $query->orderBy($sortBy, $sortOrder);

        $tasks = $query->paginate($request->get('per_page', 15));

        return response()->json([
            'code' => 0,
            'message' => '获取任务列表成功',
            'data' => $tasks
        ]);
    }

    /**
     * 创建任务
     */
    public function store(StoreTaskRequest $request)
    {
        $validated = $request->validated();
        $payload = array_merge($validated, [
            'tenant_id' => $request->user()->tenant_id,
            'status' => 'inactive',
        ]);

        $payload['min_fee'] = (float) $payload['min_fee'];
        $payload['max_fee'] = (float) $payload['max_fee'];
        $payload['min_age'] = (int) $payload['min_age'];
        $payload['max_age'] = (int) $payload['max_age'];

        $task = Task::create($payload);

        return response()->json([
            'code' => 0,
            'message' => '任务创建成功',
            'data' => $task->fresh(),
        ], 201);
    }

    /**
     * 获取任务详情
     */
    public function show(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->with(['applications.freelancer', 'applications.processor'])
                   ->findOrFail($id);

        return response()->json([
            'code' => 0,
            'message' => '获取任务详情成功',
            'data' => $task,
        ]);
    }

    /**
     * 更新任务
     */
    public function update(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        // 已发布的任务不能修改核心信息
        if ($task->status === 'published') {
            return response()->json([
                'code' => 403,
                'message' => '已发布的任务不能修改核心信息',
                'data' => null,
            ], 403);
        }

        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|required|string|max:32',
            'service_type' => [
                'sometimes',
                'required',
                'string',
                'max:100',
                Rule::exists('task_service_types', 'name'),
            ],
            'start_time' => 'sometimes|required|date',
            'end_time' => 'sometimes|required|date|after_or_equal:start_time',
            'settlement_cycle' => 'sometimes|required|in:daily,weekly,monthly',
            'min_fee' => 'sometimes|required|numeric|min:0',
            'max_fee' => 'sometimes|required|numeric|min:0|gte:min_fee',
            'billing_unit' => 'sometimes|required|string|max:20',
            'gender_requirement' => 'sometimes|required|in:female,male,unlimited',
            'education_requirement' => 'sometimes|required|in:unlimited,junior_high,high_school,college,bachelor,master,doctor',
            'min_age' => 'sometimes|required|integer|min:16|max:100',
            'max_age' => 'sometimes|required|integer|min:16|max:100|gte:min_age',
            'work_location' => 'sometimes|required|string|max:200',
            'work_content' => 'sometimes|required|string',
            'work_compensation' => 'sometimes|required|string',
            'work_time' => 'sometimes|required|string',
            'work_benefits' => 'nullable|string',
            'status' => 'sometimes|in:inactive,active,paused,published,completed,cancelled',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 422,
                'message' => '参数验证失败',
                'data' => $validator->errors(),
            ], 422);
        }

        $updateData = $request->only([
            'name',
            'service_type',
            'start_time',
            'end_time',
            'settlement_cycle',
            'min_fee',
            'max_fee',
            'billing_unit',
            'gender_requirement',
            'education_requirement',
            'min_age',
            'max_age',
            'work_location',
            'work_content',
            'work_compensation',
            'work_time',
            'work_benefits',
            'status',
        ]);

        if ($request->has('min_fee')) {
            $updateData['min_fee'] = (float) $request->input('min_fee');
        }
        if ($request->has('max_fee')) {
            $updateData['max_fee'] = (float) $request->input('max_fee');
        }
        if ($request->has('min_age')) {
            $updateData['min_age'] = (int) $request->input('min_age');
        }
        if ($request->has('max_age')) {
            $updateData['max_age'] = (int) $request->input('max_age');
        }

        $task->update($updateData);

        return response()->json([
            'code' => 0,
            'message' => '任务更新成功',
                'data' => $task->fresh()->load('applications.freelancer'),
        ]);
    }

    public function updateStatus(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        $validator = Validator::make($request->all(), [
            'status' => 'required|in:inactive,active',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 422,
                'message' => '参数验证失败',
                'data' => $validator->errors(),
            ], 422);
        }

        $task->status = $request->input('status');
        $task->save();

        return response()->json([
            'code' => 0,
            'message' => '任务状态更新成功',
            'data' => [
                'id' => $task->id,
                'status' => $task->status,
            ],
        ]);
    }

    public function qrCode(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        $freelancerScheme = config('app.freelancer_scheme');
        $freelancerDomain = config('app.freelancer_domain');
        $targetUrl = sprintf('%s://%s/task/%s', $freelancerScheme, $freelancerDomain, $task->id);

        $qrImage = base64_encode(
            QrCode::format('png')
                ->size(240)
                ->margin(2)
                ->generate($targetUrl)
        );

        return response()->json([
            'code' => 0,
            'message' => '获取任务二维码成功',
            'data' => [
                'task_id' => (string) $task->id,
                'task_name' => $task->name,
                'qr_url' => $targetUrl,
                'qr_image_base64' => $qrImage,
            ],
        ]);
    }

    /**
     * 发布任务
     */
    public function publish(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        if ($task->status !== 'draft') {
            return response()->json([
                'success' => false,
                'message' => '只有草稿状态的任务才能发布'
            ], 403);
        }

        // 验证任务信息完整性
        $requiredFields = ['name', 'service_type', 'start_time', 'end_time', 'location', 'content'];
        foreach ($requiredFields as $field) {
            if (empty($task->$field)) {
                return response()->json([
                    'success' => false,
                    'message' => "任务信息不完整，缺少：{$field}"
                ], 422);
            }
        }

        $task->update([
            'status' => 'published',
            'published_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => '任务发布成功',
            'data' => $task->fresh()
        ]);
    }

    /**
     * 暂停任务
     */
    public function pause(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        if ($task->status !== 'published') {
            return response()->json([
                'success' => false,
                'message' => '只有已发布的任务才能暂停'
            ], 403);
        }

        $task->update(['status' => 'paused']);

        return response()->json([
            'success' => true,
            'message' => '任务已暂停',
            'data' => $task->fresh()
        ]);
    }

    /**
     * 恢复任务
     */
    public function resume(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        if ($task->status !== 'paused') {
            return response()->json([
                'success' => false,
                'message' => '只有暂停的任务才能恢复'
            ], 403);
        }

        $task->update(['status' => 'published']);

        return response()->json([
            'success' => true,
            'message' => '任务已恢复',
            'data' => $task->fresh()
        ]);
    }

    /**
     * 完成任务
     */
    public function complete(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        if (!in_array($task->status, ['published', 'paused'])) {
            return response()->json([
                'success' => false,
                'message' => '只有已发布或暂停的任务才能完成'
            ], 403);
        }

        $task->update([
            'status' => 'completed',
            'completed_at' => now()
        ]);

        return response()->json([
            'success' => true,
            'message' => '任务已完成',
            'data' => $task->fresh()
        ]);
    }

    /**
     * 取消任务
     */
    public function cancel(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'reason' => 'required|string|max:500'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        if (in_array($task->status, ['completed', 'cancelled'])) {
            return response()->json([
                'success' => false,
                'message' => '已完成或已取消的任务不能再次取消'
            ], 403);
        }

        $task->update([
            'status' => 'cancelled',
            'cancelled_at' => now(),
            'cancel_reason' => $request->reason
        ]);

        return response()->json([
            'success' => true,
            'message' => '任务已取消',
            'data' => $task->fresh()
        ]);
    }

    /**
     * 删除任务
     */
    public function destroy(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        // 只有草稿状态的任务才能删除
        if ($task->status !== 'draft') {
            return response()->json([
                'success' => false,
                'message' => '只有草稿状态的任务才能删除'
            ], 403);
        }

        $task->delete();

        return response()->json([
            'success' => true,
            'message' => '任务删除成功'
        ]);
    }

    /**
     * 生成任务二维码
     */
    public function generateQrCode(Request $request, $id)
    {
        $task = Task::where('tenant_id', $request->user()->tenant_id)
                   ->findOrFail($id);

        if ($task->status !== 'published') {
            return response()->json([
                'success' => false,
                'message' => '只有已发布的任务才能生成二维码'
            ], 403);
        }

        // 生成任务报名链接
        $applicationUrl = config('app.frontend_url') . '/tasks/' . $task->id . '/apply';
        
        // 生成二维码
        $qrCode = QrCode::format('png')
                       ->size(300)
                       ->margin(2)
                       ->generate($applicationUrl);

        // 保存二维码到存储
        $filename = 'qrcodes/task_' . $task->id . '_' . time() . '.png';
        Storage::disk('public')->put($filename, $qrCode);
        
        $qrCodeUrl = Storage::disk('public')->url($filename);

        // 更新任务二维码URL
        $task->update(['qr_code_url' => $qrCodeUrl]);

        return response()->json([
            'success' => true,
            'message' => '二维码生成成功',
            'data' => [
                'qr_code_url' => $qrCodeUrl,
                'application_url' => $applicationUrl
            ]
        ]);
    }

    /**
     * 获取任务统计信息
     */
    public function statistics(Request $request)
    {
        $tenantId = $request->user()->tenant_id;
        
        $stats = [
            'total' => Task::where('tenant_id', $tenantId)->count(),
            'draft' => Task::where('tenant_id', $tenantId)->where('status', 'draft')->count(),
            'published' => Task::where('tenant_id', $tenantId)->where('status', 'published')->count(),
            'paused' => Task::where('tenant_id', $tenantId)->where('status', 'paused')->count(),
            'completed' => Task::where('tenant_id', $tenantId)->where('status', 'completed')->count(),
            'cancelled' => Task::where('tenant_id', $tenantId)->where('status', 'cancelled')->count(),
        ];

        // 本月新增任务
        $stats['this_month'] = Task::where('tenant_id', $tenantId)
                                  ->whereMonth('created_at', now()->month)
                                  ->whereYear('created_at', now()->year)
                                  ->count();

        // 今日新增任务
        $stats['today'] = Task::where('tenant_id', $tenantId)
                             ->whereDate('created_at', now()->toDateString())
                             ->count();

        return response()->json([
            'success' => true,
            'data' => $stats
        ]);
    }

    /**
     * 批量操作任务
     */
    public function batchAction(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'task_ids' => 'required|array|min:1',
            'task_ids.*' => 'integer|exists:tasks,id',
            'action' => 'required|in:publish,pause,resume,cancel,delete',
            'reason' => 'required_if:action,cancel|string|max:500'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $tasks = Task::where('tenant_id', $request->user()->tenant_id)
                    ->whereIn('id', $request->task_ids)
                    ->get();

        $successCount = 0;
        $errors = [];

        foreach ($tasks as $task) {
            try {
                switch ($request->action) {
                    case 'publish':
                        if ($task->status === 'draft') {
                            $task->update(['status' => 'published', 'published_at' => now()]);
                            $successCount++;
                        } else {
                            $errors[] = "任务 {$task->name} 不是草稿状态，无法发布";
                        }
                        break;
                    case 'pause':
                        if ($task->status === 'published') {
                            $task->update(['status' => 'paused']);
                            $successCount++;
                        } else {
                            $errors[] = "任务 {$task->name} 不是已发布状态，无法暂停";
                        }
                        break;
                    case 'resume':
                        if ($task->status === 'paused') {
                            $task->update(['status' => 'published']);
                            $successCount++;
                        } else {
                            $errors[] = "任务 {$task->name} 不是暂停状态，无法恢复";
                        }
                        break;
                    case 'cancel':
                        if (!in_array($task->status, ['completed', 'cancelled'])) {
                            $task->update([
                                'status' => 'cancelled',
                                'cancelled_at' => now(),
                                'cancel_reason' => $request->reason
                            ]);
                            $successCount++;
                        } else {
                            $errors[] = "任务 {$task->name} 已完成或已取消，无法再次取消";
                        }
                        break;
                    case 'delete':
                        if ($task->status === 'draft') {
                            $task->delete();
                            $successCount++;
                        } else {
                            $errors[] = "任务 {$task->name} 不是草稿状态，无法删除";
                        }
                        break;
                }
            } catch (\Exception $e) {
                $errors[] = "任务 {$task->name} 操作失败：" . $e->getMessage();
            }
        }

        return response()->json([
            'success' => true,
            'message' => "批量操作完成，成功处理 {$successCount} 个任务",
            'data' => [
                'success_count' => $successCount,
                'total_count' => count($tasks),
                'errors' => $errors
            ]
        ]);
    }
}
